package cn.tradewin.advisor.pages.security;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import org.slf4j.Logger;

import cn.tradewin.advisor.exceptions.DBException;
import cn.tradewin.advisor.persist.model.Permissions;
import cn.tradewin.advisor.persist.model.Roles;
import cn.tradewin.advisor.persist.services.AdvisorSecurityService;

public class RolePerms {
	
	@Inject
	private Messages messages;
	
	@Inject
	private BeanModelSource beanModelSource;
	
	@Property
	private BeanModel<Permissions> beanModel;
	
	private String roleId;
	
	@Property
	private String caption;
	
	@Property
	private Roles role;
	
	@Property
	private List<Permissions> authorizedPerms;
	
	@Property
	private List<Permissions> availablePerms;
	
	@Property
	private Permissions authorized;
	
	@Property
	private Permissions available;
	
	@Inject
	private AdvisorSecurityService securityService;
	
	@Inject
	private Logger log;
	
	void onActivate(String roleId) throws DBException {
		this.roleId = roleId;
	}

	String onPassivate() {
		return this.roleId;
	}
	
	@Log
	@SetupRender
	void setupRender() throws DBException {
		beanModel = beanModelSource.createDisplayModel(Permissions.class, messages);
		beanModel.add("action", null);
		beanModel.include("permId", "permName", "permDesc", "action");
		beanModel.get("action").sortable(false);
		
		role = securityService.findRole(roleId);
		caption = messages.format("caption", role.getRoleName());
	}
	
	@OnEvent(EventConstants.PREPARE_FOR_RENDER)
	@Log
	void prepareForRender() {
		try {
			authorizedPerms = securityService.getAuthorizedPermsForRole(roleId);
			availablePerms = securityService.getAvailablePermsForRole(roleId);
		} catch (DBException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	void onAdd(String permId) {
		try {
			securityService.addPermToRole(roleId, permId);
		} catch (DBException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e.getMessage());
		}
	}
	
	void onDelete(String permId) {
		try {
			securityService.removePermFromRole(roleId, permId);
		} catch (DBException e) {
			throw new RuntimeException(e.getMessage());
		}
	}	
}
